package com.weme.google

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task


/**
 * @author Mr.w 2022/4/18.
 *
 * 谷歌登录类
 *
 */
object GoogleLoginHelper {

    const val RC_SIGN_IN = 10010

    private const val key = "32672753781-p4bpu0lrlt0jh77oe6qofcje0j851sh5.apps.googleusercontent.com"

    private val gso by lazy {
        GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(key)
            .requestEmail()
            .build()
    }

    /**
     * 返回google 跳转intent
     * */
    fun createGoogleIntent(ctx: Context): Intent {
        val client = GoogleSignIn.getClient(ctx, gso)
        return client.signInIntent
    }

    //处理 回调
    fun handleIntent(data: Intent, result: (String,String) -> Unit, block: () -> Unit) {
        try {
            val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
            val account = task.getResult(ApiException::class.java)
            if (account == null) {
                block.invoke()
            } else {
                val idToken = account.idToken

                if (idToken == null) {
                    block.invoke()
                } else {
                    result.invoke(account.id!!,idToken)
                }
            }
        } catch (e: Exception) {
            Log.i("Main","登录谷歌失败:$e")
            block.invoke()
        }
    }

    /**
     * 初始化登录
     *
     * @params ctx 上下文
     * @params clientID Google配置分配的客户端ID
     * @params selfRequestCode 自定义请求码
     */
    fun login(ctx: FragmentActivity, success: () -> Unit) {
        val resultLauncher = ctx.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(it.data)
                val account = task.getResult(ApiException::class.java)
                if (account == null) {
                    success.invoke()
                } else {

                }
            }
        }
        val client = GoogleSignIn.getClient(ctx, gso)
        val signInIntent = client.signInIntent
        resultLauncher.launch(signInIntent)
    }

    /**
     * 退出登录
     */
    fun signOut(context: Activity, mListener: OnGoogleSignOutListener?= null) {
        val mGoogleSignInClient = GoogleSignIn.getClient(context, gso)
        mGoogleSignInClient.signOut().addOnCompleteListener(context) { mListener?.onSignOutSuccess() }
    }

    /**
     * 退出登录接口
     */
    interface OnGoogleSignOutListener {
        fun onSignOutSuccess()
    }
}